package com.dn.luckbi.controller;

import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dn.luckbi.annotation.AuthCheck;
import com.dn.luckbi.bizmq.MyMessageProducer;
import com.dn.luckbi.common.BaseResponse;
import com.dn.luckbi.common.DeleteRequest;
import com.dn.luckbi.common.ErrorCode;
import com.dn.luckbi.common.ResultUtils;
import com.dn.luckbi.constant.ChartStatusConstant;
import com.dn.luckbi.constant.CommonConstant;
import com.dn.luckbi.constant.FileConstant;
import com.dn.luckbi.constant.UserConstant;
import com.dn.luckbi.exception.BusinessException;
import com.dn.luckbi.exception.ThrowUtils;
import com.dn.luckbi.manager.AiManager;
import com.dn.luckbi.manager.RedisLimiterManager;
import com.dn.luckbi.model.dto.chart.*;
import com.dn.luckbi.model.dto.file.UploadFileRequest;
import com.dn.luckbi.model.entity.Chart;
import com.dn.luckbi.model.entity.User;
import com.dn.luckbi.model.enums.FileUploadBizEnum;
import com.dn.luckbi.model.vo.BiResponse;
import com.dn.luckbi.service.ChartService;
import com.dn.luckbi.service.UserService;
import com.dn.luckbi.utils.ExcelUtils;
import com.dn.luckbi.utils.SqlUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.time.Duration;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 帖子接口
 *
 * @author <a href="https://github.com/lidn">程序员dn</a>
 * @from <a href="https://dn.icu">yyds</a>
 */
@RestController
@RequestMapping("/chart")
//@CrossOrigin({"http://localhost:8000"})
@Slf4j
public class ChartController {

    @Resource
    private ChartService chartService;

    @Resource
    private UserService userService;

    @Resource
    private AiManager aiManager;

    @Resource
    private RedisLimiterManager redisLimiterManager;

    @Resource
    private ThreadPoolExecutor threadPoolExecutor;

    @Resource
    private MyMessageProducer myMessageProducer;




    /**
     * 创建
     *
     * @param chartAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addChart(@RequestBody ChartAddRequest chartAddRequest, HttpServletRequest request) {
        if (chartAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = new Chart();
        BeanUtils.copyProperties(chartAddRequest, chart);
//        chartService.validChart(chart, true);
        User loginUser = userService.getLoginUser(request);
        chart.setUserId(loginUser.getId());
        boolean result = chartService.save(chart);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        long newChartId = chart.getId();
        return ResultUtils.success(newChartId);
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteChart(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        Chart oldChart = chartService.getById(id);
        ThrowUtils.throwIf(oldChart == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldChart.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = chartService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新（仅管理员）
     *
     * @param chartUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateChart(@RequestBody ChartUpdateRequest chartUpdateRequest) {
        if (chartUpdateRequest == null || chartUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = new Chart();
        BeanUtils.copyProperties(chartUpdateRequest, chart);
        // 参数校验
//        chartService.validChart(chart, false);
        long id = chartUpdateRequest.getId();
        // 判断是否存在
        Chart oldChart = chartService.getById(id);
        ThrowUtils.throwIf(oldChart == null, ErrorCode.NOT_FOUND_ERROR);
        boolean result = chartService.updateById(chart);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<Chart> getChartVOById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = chartService.getById(id);
        if (chart == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(chart);
    }

    /**
     * 分页获取列表（仅管理员）
     *
     * @param chartQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Chart>> listChartByPage(@RequestBody ChartQueryRequest chartQueryRequest) {
        long current = chartQueryRequest.getCurrent();
        long size = chartQueryRequest.getPageSize();
        Page<Chart> chartPage = chartService.page(new Page<>(current, size), getQueryWrapper(chartQueryRequest));
        return ResultUtils.success(chartPage);
    }

    /**
     * 获取查询包装类
     *
     * @param chartQueryRequest
     * @return
     */
    public QueryWrapper<Chart> getQueryWrapper(ChartQueryRequest chartQueryRequest) {
        QueryWrapper<Chart> queryWrapper = new QueryWrapper<>();
        if (chartQueryRequest == null) {
            return queryWrapper;
        }
        Long id = chartQueryRequest.getId();
        Long userId = chartQueryRequest.getUserId();
        String name = chartQueryRequest.getName();
        String goal = chartQueryRequest.getGoal();
        String chartType = chartQueryRequest.getChartType();
        String sortField = chartQueryRequest.getSortField();
        String sortOrder = chartQueryRequest.getSortOrder();
        // 拼接查询条件
        queryWrapper.eq(ObjectUtils.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        queryWrapper.like(StringUtils.isNotBlank(name), "name", name);
        queryWrapper.like(StringUtils.isNotBlank(goal), "goal", goal);
        queryWrapper.like(StringUtils.isNotBlank(chartType), "chartType", chartType);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC), sortField);
        return queryWrapper;
    }


    /**
     * 分页获取列表（封装类）
     *
     * @param chartQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<Chart>> listChartVOByPage(@RequestBody ChartQueryRequest chartQueryRequest, HttpServletRequest request) {
        long current = chartQueryRequest.getCurrent();
        long size = chartQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Chart> chartPage = chartService.page(new Page<>(current, size), getQueryWrapper(chartQueryRequest));
        return ResultUtils.success(chartPage);
    }

    /**
     * 分页获取当前用户创建的资源列表
     *
     * @param chartQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<Chart>> listMyChartVOByPage(@RequestBody ChartQueryRequest chartQueryRequest, HttpServletRequest request) {
        if (chartQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        chartQueryRequest.setUserId(loginUser.getId());
        long current = chartQueryRequest.getCurrent();
        long size = chartQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Chart> chartPage = chartService.page(new Page<>(current, size), getQueryWrapper(chartQueryRequest));
        return ResultUtils.success(chartPage);
    }

    /**
     * 编辑（用户）
     *
     * @param chartEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editChart(@RequestBody ChartEditRequest chartEditRequest, HttpServletRequest request) {
        if (chartEditRequest == null || chartEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = new Chart();
        BeanUtils.copyProperties(chartEditRequest, chart);
        // 参数校验
//        chartService.validChart(chart, false);
        User loginUser = userService.getLoginUser(request);
        long id = chartEditRequest.getId();
        // 判断是否存在
        Chart oldChart = chartService.getById(id);
        ThrowUtils.throwIf(oldChart == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldChart.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = chartService.updateById(chart);
        return ResultUtils.success(result);
    }


    /**
     * 智能文件分析 (同步)
     *
     * @param multipartFile
     * @param genChartByAiRequest
     * @param request
     * @return
     */
    @PostMapping("/gen")
    public BaseResponse<BiResponse> genChartByAi(@RequestPart("file") MultipartFile multipartFile,
                                                 GenChartByAiRequest genChartByAiRequest, HttpServletRequest request) {

        // 进行ip 限流，防抖，规则为：2秒1次
        // 获取客户端 IP 地址
//        String ipAddress = request.getRemoteAddr();
//        redisLimiterManager.doRateLimit(ipAddress, 1, 20000, "请求过于频繁");

        User loginUser = userService.getLoginUser(request);
        String name = genChartByAiRequest.getName();
        String goal = genChartByAiRequest.getGoal();
        String chartType = genChartByAiRequest.getChartType();
        ThrowUtils.throwIf(StringUtils.isAnyBlank(name, goal, chartType), ErrorCode.PARAMS_ERROR, "请求参数错误");
        // 校验文件
        // 校验文件大小
        long size = multipartFile.getSize();
        final long MAX_SIZE = 1024 * 1024;
        ThrowUtils.throwIf(size > MAX_SIZE, ErrorCode.PARAMS_ERROR, "文件大小超出限制1M");
        // 校验文件名称
        String fileName = multipartFile.getOriginalFilename();
//        String suffix = ".xlsx";
//        ThrowUtils.throwIf(!fileName.endsWith(suffix), ErrorCode.PARAMS_ERROR, "文件格式错误");
        List<String> validFileSuffixList = Arrays.asList("xlsx", "xls");
        ThrowUtils.throwIf(!validFileSuffixList.contains(FileUtil.getSuffix(fileName)), ErrorCode.PARAMS_ERROR, "文件格式错误");
        // 限流
        String limitKey = "genChartByAi:" + loginUser.getId();
        int limitTime = 24 * 60 * 60;
        redisLimiterManager.doRateLimit(limitKey, 100, limitTime, "请求过于频繁");
        // 解析文件数据
        String data = ExcelUtils.excelToCsv(multipartFile);
        // 组装ai识别内容
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("分析需求：").append("\n");
        stringBuilder.append(goal)
                .append("，请使用")
                .append(chartType)
                .append("\n");
        stringBuilder.append("原始数据：").append("\n");
        stringBuilder.append(data).append("\n");

        // 调用ai获取数据
        long biModelId = 1659171950288818178L;
        String result = aiManager.doChat(biModelId, stringBuilder.toString());

        // 数据拆分
        String splitSign = "【【【【【";
        String[] split = result.split(splitSign);
        if (split.length < 3) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "Ai 调用失败请重试");
        }
        String genChart = split[1].trim();
        String genResult = split[2].trim();
        BiResponse biResponse = new BiResponse();
        biResponse.setGenChart(genChart);
        biResponse.setGenResult(genResult);

        // 插入到数据库
        Chart chart = new Chart();
        chart.setName(name);
        chart.setGoal(goal);
        chart.setChartType(chartType);
        chart.setChartData(data);
        chart.setGenChart(genChart);
        chart.setGenResult(genResult);
        chart.setUserId(loginUser.getId());
        chart.setStatus(ChartStatusConstant.SUCCEED);
        chartService.save(chart);
        // 保存id
        biResponse.setChartId(chart.getId());
        return ResultUtils.success(biResponse);
    }


    /**
     * 智能文件分析 (异步)
     *
     * @param multipartFile
     * @param genChartByAiRequest
     * @param request
     * @return
     */
    @PostMapping("/gen/async")
    public BaseResponse<BiResponse> genChartByAiAsync(@RequestPart("file") MultipartFile multipartFile,
                                                 GenChartByAiRequest genChartByAiRequest, HttpServletRequest request) {
        // 进行ip 限流，防抖，规则为：2秒1次
        // 获取客户端 IP 地址
//        String ipAddress = request.getRemoteAddr();
//        redisLimiterManager.doRateLimit(ipAddress, 1, 2, "请求过于频繁");
        User loginUser = userService.getLoginUser(request);
        String name = genChartByAiRequest.getName();
        String goal = genChartByAiRequest.getGoal();
        String chartType = genChartByAiRequest.getChartType();
        ThrowUtils.throwIf(StringUtils.isAnyBlank(name, goal, chartType), ErrorCode.PARAMS_ERROR, "请求参数错误");
        // 校验文件
        // 校验文件大小
        long size = multipartFile.getSize();
        final long MAX_SIZE = 1024 * 1024;
        ThrowUtils.throwIf(size > MAX_SIZE, ErrorCode.PARAMS_ERROR, "文件大小超出限制1M");
        // 校验文件名称
        String fileName = multipartFile.getOriginalFilename();
//        String suffix = ".xlsx";
//        ThrowUtils.throwIf(!fileName.endsWith(suffix), ErrorCode.PARAMS_ERROR, "文件格式错误");
        List<String> validFileSuffixList = Arrays.asList("xlsx", "xls");
        ThrowUtils.throwIf(!validFileSuffixList.contains(FileUtil.getSuffix(fileName)), ErrorCode.PARAMS_ERROR, "文件格式错误");
        // 限流
        String limitKey = "genChartByAi:" + loginUser.getId();
        int limitTime = 24 * 60 * 60;
        redisLimiterManager.doRateLimit(limitKey, 100, limitTime, "今天的请求次数已用完");
        // 解析文件数据
        String data = ExcelUtils.excelToCsv(multipartFile);
        // 组装ai识别内容
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("分析需求：").append("\n");
        stringBuilder.append(goal)
                .append("，请使用")
                .append(chartType)
                .append("\n");
        stringBuilder.append("原始数据：").append("\n");
        stringBuilder.append(data).append("\n");

        // 插入到数据库
        Chart chart = new Chart();
        chart.setName(name);
        chart.setGoal(goal);
        chart.setChartType(chartType);
        chart.setChartData(data);
        chart.setStatus(ChartStatusConstant.WAIT);
        chart.setUserId(loginUser.getId());
        chartService.save(chart);
        // 发送消息到消息队列
        myMessageProducer.sendMessage(chart.getId().toString());
        BiResponse biResponse = new BiResponse();
        biResponse.setChartId(chart.getId());
        // 保存id
        biResponse.setChartId(chart.getId());
        return ResultUtils.success(biResponse);
    }

    public void handleChartUpdateError(long chartId, String execMessage) {
        Chart chart = new Chart();
        chart.setId(chartId);
        chart.setStatus(ChartStatusConstant.FAILED);
        chart.setExecMessage(execMessage);
        boolean result = chartService.updateById(chart);
        if (!result) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "更新图表状态失败: " + chartId + "," + execMessage);
        }
    }


}
